/**
 * MCU 系统时钟适配 API
 * 张勇 41204@qq.com
 */

#include <stdlib.h>
#include <sys/time.h>
#include <FreeRTOS.h>
#include <task.h>

#include "sleep.h"
#include "xtime_l.h"
#include "mcu.h"

uint64_t mcu_clock_us_now() {
	XTime tCur;
	XTime_GetTime(&tCur);
	return tCur * 1000000 / COUNTS_PER_SECOND;
}

uint64_t mcu_clock_ms_now() {
	XTime tCur;
	XTime_GetTime(&tCur);
	return tCur * 1000 / COUNTS_PER_SECOND;
}

void mcu_clock_us_delay(uint32_t x) {
	usleep(x);
}

void mcu_clock_ms_delay(uint32_t x) {
#if USE_FREERTOS
	vTaskDelay((x) / portTICK_PERIOD_MS);
#else
	usleep(x * 1000);
#endif
}

static XTime _gtbase = 0;     // osSetTime() 时 XTime_GetTime() 获取的全局时钟计数值
static uint32_t _secbase = 0; // osSetTime() 时设置的从 1970-01-01 00:00:00 开始计算的秒数

uint32_t mcu_clock_get_rtcsec() {
	// 计算从上次 osSetTime() 到现在过去了多少个全局时钟计数
	XTime gt = 0;
	XTime_GetTime(&gt);
	gt = (gt > _gtbase) ? (gt - _gtbase) : (UINT64_MAX - _gtbase + gt);
	// 转换为从 1970-01-01 00:00:00 开始计算的秒数
	return _secbase + (gt / COUNTS_PER_SECOND);
}

/// @brief 设置当前时间(自1970-1-1 00:00:00至当前的秒数)
std_err_t mcu_clock_set_rtcsec(uint32_t sec) {
	XTime_GetTime(&_gtbase);
	_secbase = sec;
	return STD_ERR_OK;
}

std_err_t mcu_clock_init() {
	return STD_ERR_OK;
}
